#!/bin/sh

is_minio_installed() {
  MINIO_NAME="${MINIO_NAME:-$CLUSTER_NAME-minio}"
  MINIO_NAMESPACE="${MINIO_NAMESPACE:-$CLUSTER_NAMESPACE}"
  helm list -A | tail -n +2 | tr -s '\t ' ' ' | grep -q "$MINIO_NAME $MINIO_NAMESPACE "
}

uninstall_minio() {
  MINIO_NAME="${MINIO_NAME:-$CLUSTER_NAME-minio}"
  MINIO_NAMESPACE="${MINIO_NAMESPACE:-$CLUSTER_NAMESPACE}"
  helm uninstall --namespace "$MINIO_NAMESPACE" "$MINIO_NAME"
}

install_minio() {
  MINIO_NAME="${MINIO_NAME:-$CLUSTER_NAME-minio}"
  BUCKET_NAME="${BUCKET_NAME:-stackgres}"
  MINIO_NAMESPACE="${MINIO_NAMESPACE:-$CLUSTER_NAMESPACE}"
  kubectl create namespace "$MINIO_NAMESPACE" || true

  if printf %s "$*" | grep -qF 'tls.enabled=true'
  then
    cat << EOF > "$LOG_PATH/minio-cert.config"
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = VA
L = Somewhere
O = MyOrg
OU = MyOU
CN = MyServerName

[v3_req]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = ${MINIO_NAME}.${MINIO_NAMESPACE}
DNS.2 = ${MINIO_NAME}
EOF

    openssl genrsa -out "$LOG_PATH/minio-cert.key" 2048
    openssl req -new -x509 -nodes \
      -keyout "$LOG_PATH/minio-cert.key" \
      -out "$LOG_PATH/minio-cert.crt" \
      -config "$LOG_PATH/minio-cert.config" 
    kubectl create secret tls -n "$MINIO_NAMESPACE" "$MINIO_NAME"-certs \
      --cert="$LOG_PATH/minio-cert.crt" \
      --key="$LOG_PATH/minio-cert.key"
  fi

  cat << EOF > "$LOG_PATH/minio.yaml"
resources:
  requests:
    memory: 128Mi
persistence:
  enabled: true
  size: 128Mi
buckets:
  - name: $BUCKET_NAME
    policy: none
    purge: true
readinessProbe:
  initialDelaySeconds: 5
EOF
  if [ "$E2E_ENV" = "kind" ]
  then
    cat << EOF >> "$LOG_PATH/minio.yaml"
affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
        - matchExpressions:
          - key: "kubernetes.io/hostname"
            operator: "In"
            values: [ "${KIND_NAME}-worker", "${KIND_NAME}-control-plane" ]
EOF
  fi
  if [ "$E2E_ENV" = "minishift" ] || [ "$E2E_ENV" = "crc" ] || [ "$E2E_ENV" = "microshift" ]
  then
    if [ "$E2E_ENV" = "minishift" ]
    then
      eval "$(minishift oc-env)"
    fi
    if [ "$E2E_ENV" = "crc" ]
    then
      eval "$(crc oc-env)"
    fi
    if [ "$E2E_ENV" = "microshift" ]
    then
      alias oc="docker exec -ti '$K8S_NAME' oc"
    fi
    oc adm policy add-scc-to-user anyuid -n "$MINIO_NAMESPACE" -z "$MINIO_NAME"
    cat << EOF >> "$LOG_PATH/minio.yaml"
securityContext:
  enabled: false
EOF
  fi

  helm install --namespace "$MINIO_NAMESPACE" "$MINIO_NAME" \
    "$E2E_PATH/helm/minio-8.0.10.tgz" -f "$LOG_PATH/minio.yaml" \
    "$@"
}
